use async_std::{
    task,
    net,
    io,
    prelude::*,
};

// 处理消息收发
async fn handler(stream: net::TcpStream, addr: net::SocketAddr) -> Result<(), io::Error> {
    println!("{} accept.", addr);
    let (reader, writer) = &mut (&stream, &stream);

    let mut buff_reader = io::BufReader::new(reader);
    let mut buff = String::new();
    loop {
        match buff_reader.read_line(&mut buff).await {
            Ok(length) => {
                println!("{} read \"{}\" length {}", addr, buff.trim(), length);
                let _ = writer.write(buff.as_bytes()).await;
                buff.clear();
            }
            Err(err) => {
                println!("{} close. err: \"{}\"", addr, err);
                return Err(err);
            }
        }
    }
}

// 监听端口
async fn listen(addr: &str) -> Result<(), io::Error> {
    let listener = net::TcpListener::bind(addr).await?;
    while let Ok((stream, addr)) = listener.accept().await {
        task::spawn(handler(stream, addr));
    };
    
    Ok(())
}

#[test]
fn test_async_net(){
    let _ = task::block_on(listen("127.0.0.1:8080"));
}
